import datetime
import json
import time

import requests
import urllib3

from quote_folder.Db_connect import DB_connect


class GetCountryfee():
    def __init__(self):
        self.develop_con = DB_connect().online_db()  # 开发数据库连接
        self.develop_cur = self.develop_con.cursor()
        self.bigdata_con = DB_connect().online_big_data()  # 数据组数据库连接
        self.bigdata_cur = self.bigdata_con.cursor()
        self.add_db = DB_connect().patents_reids()

    def get_country_fee(self, sqh):
        sql = f"SELECT cost_category, pay_date FROM by_payment_information WHERE application_number = '{sqh}'"
        try:
            self.bigdata_cur.execute(sql)
            data = self.bigdata_cur.fetchall()
            return data
        except Exception as E:
            print(E)

    def t_login(self):
        headers = {"Accept": "application/json", }
        url = "https://api.xinhehonggu.com/api/auth/login"
        phone = '18866668888'
        password = '888888'
        source = 'admin'
        data = {
            'phone': phone,
            'password': password,
            'source': source,
        }
        urllib3.disable_warnings()
        r = requests.post(url=url, data=data, headers=headers, verify=False)
        res = r.text
        res_dict = json.loads(res)
        token = res_dict['data']['token']
        return token

    def zy_port(self, item):
        headers = {"Accept": "application/json", }
        # url = 'http://test.api.whxhhgip.com/api/admin/financialManagement/updateAnnualFeeArriveData'  # 测试接口
        url = 'http://112.125.25.114:90/api/admin/financialManagement/updateAnnualFeeArriveData'
        # token = self.t_login()
        paid_date = item['paid_date'].strftime("%Y-%m-%d")
        data = {
            "money_type": item["money_type"],
            "application_number": item['sqh'],
            "arrive_time": paid_date,
            "arrive_money": item['money_number'],
        }
        print("data: ", data)
        r = requests.post(url=url, data=data, headers=headers, verify=False)
        print(json.loads(r.text))

    def get_ccyfee(self):
        sql = "select ccy_paid.money_type, c.money_number,c.application_number from ccy_paid" \
              " JOIN (select application_number, paid_date,sum(money_number) as money_number from ccy_paid GROUP BY application_number, paid_date) as c" \
              " on ccy_paid.application_number = c. application_number and ccy_paid.paid_date = c.paid_date where money_type like '%年费'"
        self.bigdata_cur.execute(sql)
        returndata = self.bigdata_cur.fetchall()
        count_data = len(returndata)
        return returndata, count_data

    def main(self):
        returndata, count_data = self.get_ccyfee()  # 获取公司所有已缴费年费记录明细与金额
        count = 0
        for item in returndata:
            count += 1
            print("=" * 200)
            print(f"开始处理第{count}条缴费信息，一共有{count_data}条缴费记录！")
            patent_dic = {}
            patent_dic['sqh'] = item[2]
            patent_dic['money_type'] = item[0]
            patent_dic['money_number'] = item[1]
            data = self.get_country_fee(item[2])  # 通过公司缴费申请号获取国家已缴费信息
            if data:
                data_li, paid_date_li = self.type_change(data)
                if patent_dic['money_type'] in data_li:
                    num = data_li.index(patent_dic['money_type'])  # 获取索引
                    patent_dic['paid_date'] = paid_date_li[num]
                    self.zy_port(patent_dic)  # 调接口
            else:
                self.sadd_redis(item[2])   # 将未获取到已缴费的申请号存入redis中

    def type_change(self, data):
        data_li = []
        paid_date_li = []
        for item in data:
            data_li.append(item[0])
            paid_date_li.append(item[1])
        return data_li, paid_date_li

    def sadd_redis(self, sqh):
        self.add_db.sadd("未获取到应缴费信息", sqh)


if __name__ == '__main__':
    get_fee = GetCountryfee()
    get_fee.main()
